package IO流.IO流操作.节点流;


import java.io.*;

/**
 * 1.封装拷贝
 * 2封装释放资源
 *
 * */
public class FileUtils {

    public static void main(String[] args) {
        //文件到文件
        try{
            InputStream in = new FileInputStream("haha.txt");
            OutputStream out = new FileOutputStream("dfg.txt");
            fileCopy(in,out);
        }catch (IOException e) {
            e.printStackTrace();
        }

        //文件到字节数组
        byte[] data = null;
        try{
            InputStream in = new FileInputStream("青蛙.png");
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            fileCopy(in,out);
            data = out.toByteArray();
            System.out.println(data.length);
        }catch (IOException e) {
            e.printStackTrace();
        }

        //字节数组到文件

        try{
            ByteArrayInputStream in = new ByteArrayInputStream(data);
            OutputStream out = new FileOutputStream("青蛙1.png");
            fileCopy(in,out);
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**对接输入输出流
    * @param inputStream
     * @param outputStream
    * */
    public static void fileCopy(InputStream inputStream,OutputStream outputStream) {

        try {
            byte[] bytes = new byte[20480];
            int temp;
            while ((temp = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes,0,temp);
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(inputStream,outputStream);
        }
    }

    //释放资源
   public static void close(Closeable... io){
        for (Closeable i:io){
            try {
                i.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
   }

}
